package com.ruoyi.waterManagement.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.business.waterManagement.WrStatvolH;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.business.BusinessUtils;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.waterManagement.domain.vo.RzsWrStatvolHwrVO;
import com.ruoyi.waterManagement.service.IWaterRegimeMonitoringService;
import com.ruoyi.waterManagement.service.IWrStatvolHService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 测站时段水量Controller
 * 
 * @author hwd
 * @date 2023-02-21
 */
@RestController
@RequestMapping("/WrStatvolH")
public class WrStatvolHController extends BaseController
{
    @Autowired
    private IWrStatvolHService wrStatvolHService;
    @Autowired
    private IWaterRegimeMonitoringService waterRegimeMonitoringService;
    /**
     * 查询测站时段水量列表
     */
    @RequiresPermissions("waterManagement:WrStatvolH:list")
    @GetMapping("/list")
    public TableDataInfo list(WrStatvolH wrStatvolH)
    {
        startPage();
        if (wrStatvolH.getStatHour()==null){
            wrStatvolH.setStatHour(new Date());
        }
        List<WrStatvolH> list = wrStatvolHService.selectWrStatvolHList(wrStatvolH);
        String statNm= waterRegimeMonitoringService.queryStatNm(wrStatvolH.getStatCd());
        list.forEach(WrStatvolH->WrStatvolH.setStatNm(statNm));
        return getDataTable(list);
    }

    /**
     * 导出测站时段水量列表
     */
    @RequiresPermissions("waterManagement:WrStatvolH:export")
    @Log(title = "测站时段水量", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WrStatvolH wrStatvolH)
    {
        List<WrStatvolH> list = wrStatvolHService.selectWrStatvolHList(wrStatvolH);
        ExcelUtil<WrStatvolH> util = new ExcelUtil<WrStatvolH>(WrStatvolH.class);
        util.exportExcel(response, list, "测站时段水量数据");
    }

    /**
     * 获取测站时段水量详细信息
     */
    @RequiresPermissions("waterManagement:WrStatvolH:query")
    @GetMapping(value = "/{statCd}")
    public AjaxResult getInfo(@PathVariable("statCd") String statCd)
    {
        return success(wrStatvolHService.selectWrStatvolHByStatCd(statCd));
    }

    /**
     * 新增测站时段水量
     */
    @RequiresPermissions("waterManagement:WrStatvolH:add")
    @Log(title = "测站时段水量", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WrStatvolH wrStatvolH)
    {
        return toAjax(wrStatvolHService.insertWrStatvolH(wrStatvolH));
    }

    /**
     * 修改测站时段水量
     */
    @RequiresPermissions("waterManagement:WrStatvolH:edit")
    @Log(title = "测站时段水量", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WrStatvolH wrStatvolH)
    {
        return toAjax(wrStatvolHService.updateWrStatvolH(wrStatvolH));
    }

    /**
     * 删除测站时段水量
     */
    @RequiresPermissions("waterManagement:WrStatvolH:remove")
    @Log(title = "测站时段水量", businessType = BusinessType.DELETE)
	@DeleteMapping("/{statCds}")
    public AjaxResult remove(@PathVariable String[] statCds)
    {
        return toAjax(wrStatvolHService.deleteWrStatvolHByStatCds(statCds));
    }

//    /**
//     * 实时监测信息
//     */
//    @ApiOperation("测站实时监测信息过程线")
//    @GetMapping("/selLineMonitoringInformationByStCode")
//    public AjaxResult selLineMonitoringInformationByStCode(WrStatvolH wrStatvolH) throws Exception {
//        if (wrStatvolH.getStatHour()==null){
//            wrStatvolH.setStatHour(new Date());
//        }
//        List<WrStatvolH> channelWaterRegime = wrStatvolHService.selectWrStatvolHList(wrStatvolH);
//        ArrayList<Object> resList = new ArrayList<>();
//        //一天24条数据，每个小时出一条数据
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat sdfQueryTime = new SimpleDateFormat("yyyy-MM-dd");
//        String queryTime = sdfQueryTime.format(wrStatvolH.getStatHour());
//        //查询测站设备上报频率
//        int sb =60;
////        int time =1440/sb;
//        //按频率分钟分割时间
//        List<String> times =findDates("N",sb);
//        for (int i = 0; i < times.size()-1 ; i++) {
//            HashMap<String, Object> resMap = new HashMap<>();
//            Date start = simpleDateFormat.parse(queryTime + " " + times.get(i));
//            Date end = simpleDateFormat.parse(queryTime + " " + times.get(i + 1));
//            List<WrStatvolH> collect = channelWaterRegime.stream().filter(vo -> vo.getStatHour().getTime() >= start.getTime() && vo.getStatHour().getTime() <= end.getTime())
//                    .collect(Collectors.toList());
//            if (collect.size() <= 0) {
//                resMap.put("statHour", end);
//                resMap.put("hourLevel", "");
//                resMap.put("hourFlow", "");
//
//            } else {
//                resMap.put("statHour", end);
//                resMap.put("hourLevel", collect.get(0).getHourLevel() == null ? "" : collect.get(0).getHourLevel());
//                resMap.put("hourFlow", collect.get(0).getHourFlow() == null ? "" : collect.get(0).getHourFlow());
//            }
//            resList.add(resMap);
//        }
//        return AjaxResult.success(resList);
//    }


    /**
     * 统计测站水量日逐时
     */
    @DataScope(organAlias = "wob")
    @GetMapping("/listWrStatvolHwr")
    public AjaxResult list(RzsWrStatvolHwrVO rzsWrStatvolHwrVO) {
        startPage();
        /**入参水管机构代码、日期
         */
        //判断关键参数日期是否存在
        Date wrdate = rzsWrStatvolHwrVO.getStatHour();
        if (wrdate == null || wrdate.after(DateUtils.getNowDate())) {
            //晚于当前日期或者没有日期，则改为当前日期
            rzsWrStatvolHwrVO.setStatHour(DateUtils.getNowDate());
        }
        if (StringUtils.isEmpty(rzsWrStatvolHwrVO.getOrgCd())) {
            rzsWrStatvolHwrVO.setOrgCd(null);
        }
        HashMap<String, Object> addvAndOrgCodeInfo = BusinessUtils.getAddvAndOrgCodeInfo(rzsWrStatvolHwrVO.getOrgCd());
        int grade = (int) addvAndOrgCodeInfo.get("grade");
        String resCode = (String) addvAndOrgCodeInfo.get("resCode");
        rzsWrStatvolHwrVO.setOrgCd(resCode+"%");
        List<RzsWrStatvolHwrVO> list = wrStatvolHService.selectRzsWrStatvolHwrVOList(rzsWrStatvolHwrVO);
        if (grade == 1){
            //查找下属水管机构
            resCode =  resCode + "%0000";
        }else if (grade == 2) {
            //查找下属水管机构
            resCode =resCode + "%00";
        }else if(grade ==3) {
            resCode =resCode+"%";
        }else {
            resCode = resCode;
        }
        //查找下属机构
        rzsWrStatvolHwrVO.setOrgCd(resCode);
        List<RzsWrStatvolHwrVO> orglist = wrStatvolHService.listOrgCd(rzsWrStatvolHwrVO);
        List<RzsWrStatvolHwrVO> orgnewList =new ArrayList<>();
        //遍历查询下属水管机构统计
        for (RzsWrStatvolHwrVO r:orglist
             ) {
            HashMap<String, Object> stringObjectHashMap = BusinessUtils.getAddvAndOrgCodeInfo(r.getOrgCd());
            String ro =  (String) stringObjectHashMap.get("resCode");
            List<RzsWrStatvolHwrVO> rzsWrStatvolHwrVOList = list.stream().filter(s -> s.getOrgCd().startsWith(ro)).collect(Collectors.toList());
            RzsWrStatvolHwrVO wrVoSum = new RzsWrStatvolHwrVO();
            wrVoSum.setOrgNm(r.getOrgNm());
            BigDecimal s0 = new BigDecimal("0");
            BigDecimal s1 = new BigDecimal("0");
            BigDecimal s2 = new BigDecimal("0");
            BigDecimal s3 = new BigDecimal("0");
            BigDecimal s4 = new BigDecimal("0");
            BigDecimal s5 = new BigDecimal("0");
            BigDecimal s6 = new BigDecimal("0");
            BigDecimal s7 = new BigDecimal("0");
            BigDecimal s8 = new BigDecimal("0");
            BigDecimal s9 = new BigDecimal("0");
            BigDecimal s10 = new BigDecimal("0");
            BigDecimal s11 = new BigDecimal("0");
            BigDecimal s12 = new BigDecimal("0");
            BigDecimal s13 = new BigDecimal("0");
            BigDecimal s14 = new BigDecimal("0");
            BigDecimal s15 = new BigDecimal("0");
            BigDecimal s16 = new BigDecimal("0");
            BigDecimal s17 = new BigDecimal("0");
            BigDecimal s18 = new BigDecimal("0");
            BigDecimal s19 = new BigDecimal("0");
            BigDecimal s20 = new BigDecimal("0");
            BigDecimal s21 = new BigDecimal("0");
            BigDecimal s22 = new BigDecimal("0");
            BigDecimal s23 = new BigDecimal("0");
            BigDecimal sc = new BigDecimal("0");
            if (rzsWrStatvolHwrVOList.size()>0){
              for (RzsWrStatvolHwrVO w : rzsWrStatvolHwrVOList
                  ) {
                    s0 = w.getS0() == null ? s0.add(new BigDecimal("0")) : s0.add(new BigDecimal(w.getS0())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s1 =  w.getS1() == null ? s1.add(new BigDecimal("0")) : s1.add(new BigDecimal(w.getS1())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s2 =  w.getS2() == null ? s2.add(new BigDecimal("0")) : s2.add(new BigDecimal(w.getS2())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s3 =  w.getS3() == null ? s3.add(new BigDecimal("0")) : s3.add(new BigDecimal(w.getS3())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s4 =  w.getS4() == null ? s4.add(new BigDecimal("0")) : s4.add(new BigDecimal(w.getS4())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s5 =  w.getS5() == null ? s5.add(new BigDecimal("0")) : s5.add(new BigDecimal(w.getS5())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s6 =  w.getS6() == null ? s6.add(new BigDecimal("0")) : s6.add(new BigDecimal(w.getS6())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s7 =  w.getS7() == null ? s7.add(new BigDecimal("0")) : s7.add(new BigDecimal(w.getS7())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s8 =  w.getS8() == null ? s8.add(new BigDecimal("0")) : s8.add(new BigDecimal(w.getS8())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s9 =  w.getS9() == null ? s9.add(new BigDecimal("0")) : s9.add(new BigDecimal(w.getS9())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s10 =  w.getS10() == null ? s10.add(new BigDecimal("0")) : s10.add(new BigDecimal(w.getS10())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s11 =  w.getS11() == null ? s11.add(new BigDecimal("0")) : s11.add(new BigDecimal(w.getS11())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s12 =  w.getS12() == null ? s12.add(new BigDecimal("0")) : s12.add(new BigDecimal(w.getS12())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s13 =  w.getS13() == null ? s13.add(new BigDecimal("0")) : s13.add(new BigDecimal(w.getS13())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s14 =  w.getS14() == null ? s14.add(new BigDecimal("0")) : s14.add(new BigDecimal(w.getS14())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s15 =  w.getS15() == null ? s15.add(new BigDecimal("0")) : s15.add(new BigDecimal(w.getS15())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s16 =  w.getS16() == null ? s16.add(new BigDecimal("0")) : s16.add(new BigDecimal(w.getS16())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s17 =  w.getS17() == null ? s17.add(new BigDecimal("0")) : s17.add(new BigDecimal(w.getS17())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s18 =  w.getS18() == null ? s18.add(new BigDecimal("0")) : s18.add(new BigDecimal(w.getS18())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s19 =  w.getS19() == null ? s19.add(new BigDecimal("0")) : s19.add(new BigDecimal(w.getS19())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s20 =  w.getS20() == null ? s20.add(new BigDecimal("0")) : s20.add(new BigDecimal(w.getS20())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s21 =  w.getS21() == null ? s21.add(new BigDecimal("0")) : s21.add(new BigDecimal(w.getS21())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s22 =  w.getS22() == null ? s22.add(new BigDecimal("0")) : s22.add(new BigDecimal(w.getS22())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    s23 =  w.getS23() == null ? s23.add(new BigDecimal("0")) : s23.add(new BigDecimal(w.getS23())).setScale(4, BigDecimal.ROUND_HALF_UP);
                    sc =  w.getSc() == null ? sc.add(new BigDecimal("0")) : sc.add(new BigDecimal(w.getSc()));
                }
            }
                wrVoSum.setOrgCd("合计");
                wrVoSum.setS0(s0.toString());
                wrVoSum.setS1(s1.toString());
                wrVoSum.setS2(s2.toString());
                wrVoSum.setS3(s3.toString());
                wrVoSum.setS4(s4.toString());
                wrVoSum.setS5(s5.toString());
                wrVoSum.setS6(s6.toString());
                wrVoSum.setS7(s7.toString());
                wrVoSum.setS8(s8.toString());
                wrVoSum.setS9(s9.toString());
                wrVoSum.setS10(s10.toString());
                wrVoSum.setS11(s11.toString());
                wrVoSum.setS12(s12.toString());
                wrVoSum.setS13(s13.toString());
                wrVoSum.setS14(s14.toString());
                wrVoSum.setS15(s15.toString());
                wrVoSum.setS16(s16.toString());
                wrVoSum.setS17(s17.toString());
                wrVoSum.setS18(s18.toString());
                wrVoSum.setS19(s19.toString());
                wrVoSum.setS20(s20.toString());
                wrVoSum.setS21(s21.toString());
                wrVoSum.setS22(s22.toString());
                wrVoSum.setS23(s23.toString());
                wrVoSum.setSc(sc.toString());
                orgnewList.add(0, wrVoSum);

        }
        orgnewList.removeAll(Collections.singleton(null));
        //将数据结果放入map中区分时
        Collections.reverse(orgnewList);
        return AjaxResult.success(orgnewList);
    }


    /**
     * 按照指定小时分割时间段
     * @param dateType 类型 M/D/H/N -->每月/每天/每小时/每分钟
     * @param time 指定小时(如：1、2、3、4)
     * @return
     */
    public static List<String> findDates(String dateType, int time) throws Exception {
        List<String> listDate = new ArrayList<>();
        Date start =startTime(new Date());
        Date end =endTime(new Date());
        listDate.add(new SimpleDateFormat("00:00:00").format(start));
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(start);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(end);
        while (calEnd.after(calBegin)) {
            if ("H".equals(dateType)){
                calBegin.add(Calendar.HOUR, time);
            }
            if ("M".equals(dateType)){
                calBegin.add(Calendar.MONTH, time);
            }
            if ("D".equals(dateType)){
                calBegin.add(Calendar.DATE, time);
            }
            if ("N".equals(dateType)){
                calBegin.add(Calendar.MINUTE , time);
            }
            if (calEnd.after(calBegin)){
                listDate.add(new SimpleDateFormat("HH:mm:01").format(calBegin.getTime()));
            }
            else{
                //  listDate.add(new SimpleDateFormat("HH:mm:00").format(calEnd.getTime()));
            }


        }
        listDate.add(new SimpleDateFormat("23:59:59").format(calEnd.getTime()));
        return listDate;
    }

    public static Date startTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    public static Date endTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 59);
        return cal.getTime();
    }
}
